#include "stdafx.h"

#include "FASTClientMessageInterpreter.h"
#include "ConsoleLock.h"

using namespace QuickFAST;

////////////////////////
// MessageInterpreter
FASTClientMessageInterpreter::FASTClientMessageInterpreter(std::ostream & out, bool silent)
  : formatter_(out)
  , out_(out)
  , indent_(0)
  , recordCount_(0)
  , logLevel_(Common::Logger::QF_LOG_VERBOSE)
  , silent_(silent)
{
}

FASTClientMessageInterpreter::~FASTClientMessageInterpreter()
{
}

bool
FASTClientMessageInterpreter::wantLog(unsigned short level)
{
  return level <= logLevel_;
}

bool
FASTClientMessageInterpreter::logMessage(unsigned short level, const std::string & logMessage)
{
  if(level <= logLevel_)
  {
    boost::mutex::scoped_lock lock(FASTClientConsoleLock::consoleMutex);
    std::cerr << logMessage << std::endl;
  }
  return true;
}


bool
FASTClientMessageInterpreter::reportDecodingError(const std::string & errorMessage)
{
  boost::mutex::scoped_lock lock(FASTClientConsoleLock::consoleMutex);
  std::cerr << "Decoding error: " << errorMessage << std::endl;
  return false;
}

bool
FASTClientMessageInterpreter::reportCommunicationError(const std::string & errorMessage)
{
  boost::mutex::scoped_lock lock(FASTClientConsoleLock::consoleMutex);
  std::cerr << "Communication error: " << errorMessage << std::endl;
  return false;
}

void
FASTClientMessageInterpreter::decodingStarted()
{
  // ignore this.
}

void
FASTClientMessageInterpreter::decodingStopped()
{
  boost::mutex::scoped_lock lock(FASTClientConsoleLock::consoleMutex);
  out_ << "End of data" << std::endl;
}


bool
FASTClientMessageInterpreter::consumeMessage(Messages::Message & message)
{
  recordCount_ += 1;
  if(!silent_)
  {
    out_ << "Record #" << recordCount_ << ' ' << std::flush;
    boost::mutex::scoped_lock lock(FASTClientConsoleLock::consoleMutex);
    formatter_.formatMessage(message);
    out_ << std::endl;
  }
  return true;
}
